"""
FileName：exceptions.py
Description：
Author：gaojiahui
Time：2025/8/17 17:16
Website：https://gitee.com/gao-jiahui
"""
import time
from functools import wraps

from utils.logger import logger

"""异常处理模块"""


class AutomationError(Exception):
    """自动化测试基础异常"""

    def __init__(self, message, screenshot=None, page_source=None):
        super().__init__(message)
        self.screenshot = screenshot
        self.page_source = page_source
        logger.error(f"ERROR: {message}")


class ElementNotFoundError(AutomationError):
    """元素定位异常失败"""
    pass


class TimeOutError(AutomationError):
    """操作超时异常"""
    pass


class AssertionError(AutomationError):
    """断言失败异常"""
    pass


def handle_exceptions(func):
    """异常处理装饰器"""

    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except (NoSuchElementException, ElementNotFoundError) as e:
            driver = args[0].driver if hasattr(args[0], 'driver') else None
            capture_debug_info(driver, "ELEMENT_NOT_FOUND")
            raise ElementNotFoundError(f"元素定位失败: {str(e)}")
        except (TimeOutException, TimeOutError) as e:
            driver = args[0].driver if hasattr(args[0], 'driver') else None
            capture_debug_info(driver, "TIMEOUT")
            raise TimeOutError(f"操作超时: {str(e)}")
        except AssertionError as e:
            driver = args[0].driver if hasattr(args[0], 'driver') else None
            capture_debug_info(driver, "ASSERTION_FAILED")
            raise AssertionError(f"断言失败: {str(e)}")
        except WebDriverException as e:
            driver = args[0].driver if hasattr(args[0], 'driver') else None
            capture_debug_info(driver, "WEBDRIVER_ERROR")
            raise AutomationError(f"浏览器异常: {str(e)}")
        return wrapper

def capture_debug_info(driver, error_type):
    """捕获调试信息并记录"""
    if driver:
        try:
            timestamp = time.strftime("%Y%m%d_%H%M%S")
            screenshot_path = f"screenshots/FAIL_{error_type}_{timestamp}.png"
            driver.save_screenshot(screenshot_path)

            page_source_path = f"page_source/FAIL_{error_type}_{timestamp}.html"
            with open(page_source_path, "w", encoding="utf-8") as f:
                f.write(driver.page_source)

            logger.debug(f"截图保存至: {screenshot_path}")
            logger.debug(f"页面源码保存至: {page_source_path}")
        except Exception as e:
            logger.error(f"捕获调试信息失败: {str(e)}")